<!--
 * @Description: 流程表单消息规则配置
 * @Author: DHL
 * @Date: 2022-04-18 14:45:52
 * @LastEditors: DHL
 * @LastEditTime: 2023-08-08 14:36:35
-->

<template>
  <div class="process-panel-tab__content">
    <div class="process-panel-tab__content-table">
      <el-table :data="propertyList" size="small" border>
        <el-table-column type="index" label="序号" width="50px" />
        <el-table-column label="类型" prop="name" min-width="100px" show-overflow-tooltip>
          <template #default="scope">
            {{ getTypeName(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column label="内容" prop="value" min-width="100px" show-overflow-tooltip />

        <el-table-column label="操作" prop="action" width="100px" align="center">
          <template #default="scope">
            <el-button
              link
              type="warning"
              title="编辑"
              @click="handleEdit(scope.row, scope.$index)"
            >
              <svg-icon className="process-icon" iconClass="editSquare"></svg-icon>
            </el-button>

            <el-button link type="danger" title="移除" @click="handleDelete(scope.$index)">
              <svg-icon className="process-icon" iconClass="delete"></svg-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="mt10">
      <el-button type="primary" size="small" style="width: 100%" @click="handleOpen()">
        <svg-icon className="process-icon" iconClass="plus"></svg-icon>
        添加属性
      </el-button>
    </div>
  </div>

  <!-- 属性配置弹框 -->
  <tw-dialog
    v-model="formVisible"
    title="属性配置"
    width="600px"
    :showZoom="false"
    @close="handleClose"
  >
    <el-form ref="dbFormRef" :model="dbForm" label-width="90px">
      <el-form-item label="消息类型" prop="name">
        <el-select v-model="dbForm.type" clearable placeholder="请选择类型">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <template v-if="dbForm.type === 'wxCpMessage'">
        <el-form-item label="企业微信" prop="agentId">
          <el-select v-model="dbForm.agentId" clearable placeholder="请选择企业微信">
            <el-option
              v-for="item in wxCpConfig.appConfigs"
              :key="item.agentId"
              :label="`${item.agentId} - ${item.remark}`"
              :value="item.agentId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="业务类型" prop="bizType">
          <el-input v-model="dbForm.bizType" placeholder="请输入业务类型" />
        </el-form-item>
      </template>

      <el-form-item label="消息内容" prop="value">
        <el-input v-model="dbForm.value" autosize type="textarea" placeholder="请输入内容" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose()">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()">确 定</el-button>
    </template>
  </tw-dialog>
</template>

<script lang="ts">
  export default { name: 'PanelFormMessageConfig' }
</script>

<script setup lang="ts">
  import { nextTick, onMounted, reactive, ref, watch } from 'vue'
  import { useBpmnStore } from '../../store/bpmn'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { assign, cloneDeep } from 'lodash-es'
  import { apiTenantConfigGetByType } from '@/api/system/tenantConfig'

  //////////////////////////////////////////////////
  // 属性
  //////////////////////////////////////////////////
  const bpmnStore = useBpmnStore()

  const propertyList = ref([] as Array<any>)

  let propertyIndex = -1

  watch(
    () => bpmnStore.activatedElementId,
    (newVal) => {
      if (newVal) {
        nextTick(() => {
          handleInit()
        })
      }
    },
    {
      immediate: true
    }
  )

  //////////////////////////////////////////////////
  // 消息类型
  //////////////////////////////////////////////////

  /**
   * 消息类型
   */
  const typeOptions = ref([
    { label: '标题', value: 'title' },
    { label: '系统消息', value: 'systemMessage' },
    { label: '微信企业号消息', value: 'wxCpMessage' },
    { label: '微信服务号消息', value: 'wxMpMessage' }
  ])

  // 创建一个空的 Map
  const typeOptionsMap = new Map()

  // 遍历数组并将数据添加到 Map
  for (const option of typeOptions.value) {
    typeOptionsMap.set(option.value, option.label)
  }

  /**
   * 获取类型名称
   */
  function getTypeName(key: string) {
    return typeOptionsMap.get(key)
  }

  //////////////////////////////////////////////////
  // 函数
  //////////////////////////////////////////////////

  /**
   * 初始化
   */
  function handleInit() {
    propertyList.value = cloneDeep(bpmnStore.getFormMessageConfig)
  }

  /**
   * 新增
   */
  function handleOpen() {
    formVisible.value = true
    propertyIndex = -1

    assign(dbForm, {
      name: '',
      type: '',
      value: '',
      bizType: '', // 业务类型，用于消息点击后跳转页面
      agentId: ''
    })
  }

  /**
   * 编辑
   * @param row
   * @param index
   */
  function handleEdit(row: any, index: number) {
    formVisible.value = true
    propertyIndex = index
    assign(dbForm, cloneDeep(row))
  }

  /**
   * 删除
   * @param index
   */
  function handleDelete(index: number) {
    ElMessageBox.confirm('确认移除该属性吗?', '移除提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        propertyList.value.splice(index, 1)
        bpmnStore.setFormMessageConfig(propertyList.value)
      })
      .catch(() => {
        ElMessage.info('操作被取消了')
      })
  }

  //////////////////////////////////////////////////
  // 属性表单
  //////////////////////////////////////////////////
  const formVisible = ref(false)

  const dbFormRef = ref()

  const dbForm = reactive({
    name: '',
    type: '',
    value: '',
    bizType: '', // 业务类型，用于消息点击后跳转页面
    agentId: ''
  })

  /**
   * 关闭弹框
   */
  function handleClose() {
    formVisible.value = false
  }

  /**
   * 属性提交
   */
  function handleSubmit() {
    const { name, value } = dbForm

    if (propertyIndex === -1) {
      // 新建属性字段

      const exist = propertyList.value.some((item) => {
        return item.value === value
      })

      if (exist) {
        ElMessage.warning(`${name}已存在`)
        return
      }

      propertyList.value.push(cloneDeep(dbForm))
    } else {
      propertyList.value.splice(propertyIndex, 1, cloneDeep(dbForm))
    }

    bpmnStore.setFormMessageConfig(propertyList.value)

    handleClose()
  }

  //////////////////////////////////////////////////
  // 查询租户配置
  //////////////////////////////////////////////////

  const wxCpConfig = reactive({
    id: '',
    unionId: '',
    appConfigs: [] as Array<any>
  })

  /**
   * 查询租户配置
   */
  function handleSearchTenantConfig() {
    apiTenantConfigGetByType('WX_CP').then((result) => {
      if (result?.success) {
        const config = JSON.parse(result.data?.configJson || '')

        wxCpConfig.id = result.data.id || ''
        wxCpConfig.unionId = result.data.unionId || ''
        wxCpConfig.appConfigs = config.appConfigs
      }
    })
  }

  //////////////////////////////////////////////////
  // 生命周期
  //////////////////////////////////////////////////
  onMounted(() => {
    handleSearchTenantConfig()
  })
</script>
